import datetime
import json

from commonTool.entity import Ttt
from commonTool.logs.logs_wrapper import LogUtil

logs = LogUtil(mode=1, path='../logs')


class ClassConvertTool:

    @staticmethod
    @logs
    def convertJson(c_object: object):
        result = {}
        fields = []
        try:
            fields = c_object.all()
        except AttributeError as e:
            logs.warning(e)
        for field in fields:
            # print('---->', field)
            try:  # 处理异常
                value = getattr(c_object, field)
                if value:
                    if isinstance(value, datetime.datetime):
                        value = value.strftime("%Y-%m-%d %H:%M:%S")
                    result[field] = value
            except Exception as e:
                logs.warning(f'Check the {field} is in the all() method ?', e)
        print(result)
        return json.dumps(result)

    @staticmethod
    @logs
    def convertCustomJson(c_object: object, fields: list):
        result = {}
        for field in fields:
            try:  # 处理异常
                value = getattr(c_object, field)
                if value:
                    result[field] = value
            except Exception as e:
                logs.warning(f'Check the {field} is in the all() method ?', e)
        return json.dumps(result)

    @staticmethod
    @logs
    def jsonConvertClass(jsonStr: str, c_object: object):
        result = c_object
        jsonStr = json.loads(jsonStr)
        for field in jsonStr:
            # if hasattr(c_object, field):
            setattr(c_object, field, jsonStr[field])
        return result
